package util;

import java.awt.TextField;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class DefaultKeyActionListner implements KeyListener {

    private final TextField textField;

    public DefaultKeyActionListner(TextField textField) {
        this.textField = textField;
    }

    public void keyTyped(KeyEvent e) {
    //System.out.println("oi keyTyped: " + e.getKeyChar());
    }

    public void keyReleased(KeyEvent e) {
    //System.out.println("oi keyReleased:" + e.getKeyChar() + " keyCode: " + e.getKeyCode());
    }

    public void keyPressed(KeyEvent e) {
        // System.out.println("oi keyPressed: " + e.getKeyChar() + " keyCode: " + e.getKeyCode());
        String text = textField.getText();
        //        System.out.println(textField.getSelectionStart() + " " + textField.getSelectionEnd());
        //        System.out.println(textField.getSelectedText());
        switch (e.getKeyCode()) {
            case KeyEvent.VK_BACK_SPACE:
                //                System.out.println("back");
                if (text.length() == 0) {
                    return;
                }
                if (textField.getSelectionEnd() > 0) {
                    String sub = text.substring(0, textField.getSelectionStart());
                    sub += text.substring(textField.getSelectionEnd(), text.length());
                    textField.setText(sub);
                } else {
                    textField.setText(text.substring(0, text.length() - 1));
                }
                break;
            default:
                textField.setText(text + e.getKeyChar());
                break;
        }
    }

}
